package com.client.ryt.activity;

import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.client.ryt.R;
import com.client.ryt.basic.BaseActivity;
import com.client.ryt.basic.BaseApplication;
import com.client.ryt.basic.BaseException;
import com.client.ryt.basic.BaseLiteners;
import com.client.ryt.basic.BaseResponse;
import com.client.ryt.basic.BaseTask;
import com.client.ryt.config.LoginConfig;
import com.client.ryt.task.http.request.LoginOutRequest;


public class MainActivity extends BaseActivity {

    MainActivity oThis =this;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            new BaseTask<LoginOutRequest,BaseResponse>(oThis,LoginOutRequest.class,BaseResponse.class,null,new BaseLiteners.BaseResponseListener() {
                @Override
                public void OnFail(BaseException e) {
                    showToast(e.getErrmsg());
                }

                @Override
                public void OnSuccess(BaseResponse o) {
                    if(o.getIsSuccess()){
                        LoginConfig.clearToken();
                        Intent intent = new Intent(oThis,LoginActivity.class);
                        startActivity(intent);
                        oThis.finish();
                    }
                }
            },false).execute();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /******************************************双击退出***********************************/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_MENU)) {
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isExit) {
                isExit = true;
                showToast("再按一次退入后台运行");
                // 利用handler延迟发送更改状态信息
                mHandler.sendEmptyMessageDelayed(0, 2000);
            } else {
                PackageManager pm = getPackageManager();
                ResolveInfo homeInfo = pm.resolveActivity(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME), 0);
                ActivityInfo ai = homeInfo.activityInfo;
                Intent startIntent = new Intent(Intent.ACTION_MAIN);
                startIntent.addCategory(Intent.CATEGORY_LAUNCHER);
                startIntent.setComponent(new ComponentName(ai.packageName, ai.name));
                startActivitySafely(startIntent);
                return true;
            }
        }
        return false;
    }
    private void startActivitySafely(Intent intent) {
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, "null",
                    Toast.LENGTH_SHORT).show();
        } catch (SecurityException e) {
            Toast.makeText(this, "null",
                    Toast.LENGTH_SHORT).show();
        }
    }
    boolean isExit = false;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };



    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment implements View.OnClickListener {

        public PlaceholderFragment() {}

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            rootView.findViewById(R.id.ll_cash).setOnClickListener(this);
            rootView.findViewById(R.id.ll_buyscore).setOnClickListener(this);
            rootView.findViewById(R.id.ll_traderecord).setOnClickListener(this);
            rootView.findViewById(R.id.ll_check).setOnClickListener(this);
            ((TextView)rootView.findViewById(R.id.tv_shopname)).setText(LoginConfig.getLoginConfig().getShopMember().getShopname());
            ((TextView)rootView.findViewById(R.id.tv_username)).setText(LoginConfig.getLoginConfig().getShopMember().getUsername());
            return rootView;
        }

        @Override
        public void onClick(View view) {
            Intent it;
            switch (view.getId()){
                case R.id.ll_cash:
                    it = new Intent(this.getActivity(),CashDoneActivity.class);
                    startActivity(it);
                    break;
                case R.id.ll_buyscore:
                    it = new Intent(this.getActivity(),BuyScoreActivity.class);
                    startActivity(it);
                    break;
                case R.id.ll_traderecord:
                    it = new Intent(this.getActivity(),TradeRecordListActivity.class);
                    startActivity(it);
                    break;
                case R.id.ll_check:
                    it = new Intent(this.getActivity(),StatementActivity.class);
                    startActivity(it);
                    break;
            }
        }
    }
}
